import {ref, onMounted, onUnmounted, nextTick, watch} from 'vue'
import { userStore } from '/src/components/store/index.js'
import { messageStore } from '/src/components/store/message.js'
import {ElMessage} from "element-plus";
import request from "@/utils/request.js";

export function useWebSocket() {
    const userItemStore = userStore()
    const messageItemStore = messageStore()

    const ws = ref(null)
    const isConnected = ref(false)
    const reconnectAttempts = ref(0)
    const maxReconnectAttempts = 5
    const reconnectInterval = 3000
    const messageCallbacks = ref([])
    const wsReadyState = ref(0)
    const activeSubscriptions = ref(new Set()) // 跟踪当前订阅的对话

    const connect = () => {
        if (!userItemStore.user.token) {
            console.error('无法建立WebSocket连接：缺少token')
            return
        }

        if (ws.value) {
            ws.value.close()
        }

        try {
            ws.value = new WebSocket(`ws://localhost:9091/ws/chat`)

            ws.value.onopen = () => {
                isConnected.value = true
                reconnectAttempts.value = 0
                console.log('WebSocket连接成功')
                wsReadyState.value = WebSocket.OPEN;


                // 认证
                ws.value.send(JSON.stringify({
                    action: "login",
                    token: userItemStore.user.token
                }))



                // 重新订阅所有活跃对话
                activeSubscriptions.value.forEach(conversationId => {
                    subscribe(conversationId)
                })
            }

            ws.value.onmessage = (event) => {
                handleMessage(event)
            }

            ws.value.onclose = (event) => {
                isConnected.value = false
                console.log(`连接关闭: code=${event.code}, reason=${event.reason}`)
                wsReadyState.value = WebSocket.CLOSED

                const delay = Math.min(
                    reconnectInterval * Math.pow(2, reconnectAttempts.value),
                    30000
                )
                reconnectAttempts.value++
                console.log(`尝试重连 (${reconnectAttempts.value}): 延迟 ${delay}ms`)
                setTimeout(connect, delay)
            }

            ws.value.onerror = (error) => {
                console.error('WebSocket错误:', error)
                ws.value.close()
            }

        } catch (error) {
            console.error('创建连接失败:', error)
            setTimeout(connect, reconnectInterval)
        }
    }

    // 订阅对话
    // 修改subscribe函数
    const subscribe = async (conversationId) => {
        if (!conversationId) {
            console.error('订阅失败: 缺少conversationId');
            return false;
        }

        // 确保连接就绪
        if (!ws.value || ws.value.readyState !== WebSocket.OPEN) {
            console.log('WebSocket未连接，尝试连接...');
            await connect();

            // 等待连接就绪
            await new Promise(resolve => {
                const checkInterval = setInterval(() => {
                    if (ws.value && ws.value.readyState === WebSocket.OPEN) {
                        clearInterval(checkInterval);
                        resolve();
                    }
                }, 100);
            });
        }

        try {
            ws.value.send(JSON.stringify({
                action: "subscribe",
                conversationId: conversationId,
                token: localStorage.getItem('token')
            }));

            activeSubscriptions.value.add(conversationId);
            console.log(`成功订阅对话 ${conversationId}`);
            return true;
        } catch (error) {
            console.error('订阅失败:', error);
            return false;
        }
    };
    // const subscribe = (conversationId) => {
    //     if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    //         const message = {
    //             action: "subscribe",
    //             conversationId: conversationId,
    //             token: localStorage.getItem('token')
    //         };
    //         ws.value.send(JSON.stringify(message));
    //         console.log(`已订阅对话 ${conversationId}`);
    //         return true;
    //     }
    //     console.error('WebSocket连接未就绪，无法订阅');
    //     return false;
    // };
    // const subscribe = (conversationId) => {
    //     if (!conversationId) {
    //         console.error('订阅失败: 缺少conversationId');
    //         return false;
    //     }
    //
    //     if (!ws.value || ws.value.readyState !== WebSocket.OPEN) {
    //         console.error('订阅失败: WebSocket连接未就绪');
    //         return false;
    //     }
    //
    //     try {
    //         ws.value.send(JSON.stringify({
    //             action: "subscribe",
    //             conversationId
    //         }));
    //         activeSubscriptions.value.add(conversationId);
    //         console.log(`成功订阅对话 ${conversationId}`);
    //         return true;
    //     } catch (error) {
    //         console.error('订阅失败:', error);
    //         return false;
    //     }
    // };

    // 添加自动重订阅机制
    watch(isConnected, (newVal) => {
        if (newVal) {
            // 连接恢复时重新订阅所有对话
            activeSubscriptions.value.forEach(conversationId => {
                subscribe(conversationId);
            });
        }
    });

    // 取消订阅
    const unsubscribe = (conversationId) => {
        if (ws.value && ws.value.readyState === WebSocket.OPEN) {
            ws.value.send(JSON.stringify({
                action: "unsubscribe",
                conversationId
            }))
            activeSubscriptions.value.delete(conversationId)
            console.log(`已取消订阅对话 ${conversationId}`)
        }
    }

    const handleMessage = async(event) => {
        try {
            const message = JSON.parse(event.data)
            console.log('收到WebSocket消息:', message)

            // 心跳处理
            if (message.type === 'ping') {
                if (ws.value) {
                    ws.value.send(JSON.stringify({ type: 'pong' }))
                    console.log('发送心跳响应')
                }
                return
            }

            // 强制登出
            if (message.type === 'force_logout') {
                ElMessage.warning('您的账号在其他设备登录')
                connect()
                return
            }

            // 新消息处理
            if (message.type === 'newMessage' && message.payload) {
                const payload = message.payload
                if (!payload) {
                    console.warn('新消息缺少有效载荷')
                    return
                }


                messageItemStore.addMessage({
                    id: payload.id,
                    senderId: payload.senderId,
                    content: payload.content,
                    messageTime: payload.messageTime || new Date(),
                    conversationId: payload.conversationId,
                    sender:{
                        id: payload.senderId,
                        name:payload.sender.name,
                        avatar:payload.sender.avatar
                    }
                })

                // 检查接收者是否在线
                let isReceiverActive = false;
                // 判断接收者是否在线（当前用户是否是消息接收者）
                const isReceiver = payload.senderId== messageItemStore.mCurrentConversation.starterId;
                // 使用 try/catch 处理可能的错误
                try {
                    let response;
                    if (isReceiver) {
                        response = await request.get(`/doctor/checkIfOnline/${messageItemStore.mCurrentConversation.participantId}`);
                    } else {
                        response = await request.get(`/doctor/checkIfOnline/${messageItemStore.mCurrentConversation.starterId}`);
                    }
                    isReceiverActive = response.data;


                    if (isReceiverActive && messageItemStore.mCurrentConversation.id == payload.conversationId) {
                        messageItemStore.markAsRead(payload.conversationId, userItemStore.user.id);
                    }

                } catch (error) {
                    console.error('检查在线状态失败:', error);
                }



                //条件判断是否是接收方是否打开当前对话；如果是，标记已读；不是，不标记；
                //当前对话的ID在另外一个组件MyMessage，这里是useWebSocket组件；
                if (isReceiverActive && messageItemStore.mCurrentConversation.id==payload.conversationId) {
                    messageItemStore.markAsRead(payload.conversationId,userItemStore.user.id);
                }

                // 触发回调
                messageCallbacks.value.forEach(callback => callback(message))
                return
            }

            // 登录响应
            if (message.action === 'login') {
                handleLoginResponse(message)
                return
            }

            console.log('收到未知类型消息:', message)

        } catch (error) {
            console.error('消息解析失败:', error, '原始数据:', event.data)
            ElMessage.error('消息解析失败')
        }
    }



    const handleLoginResponse = (msg) => {
        if (msg.code === 200 && msg.user) {
            userItemStore.updateUser(msg.user)
            console.log('登录响应，用户信息已更新')
        } else {
            console.warn('登录响应错误:', msg.message)
        }
    }

    const sendMessage = (message) => {
        if (!isConnected.value || !ws.value || ws.value.readyState !== WebSocket.OPEN) {
            console.warn('发送失败: 连接未就绪')
            connect()
            return false
        }
        try {
            ws.value.send(JSON.stringify(message))
            return true
        } catch (error) {
            console.error('发送失败:', error)
            return false
        }
    }

    const startHeartbeat = () => {
        const interval = setInterval(() => {
            if (isConnected.value) {
                sendMessage({ type: 'ping' })
                console.log('发送心跳')
            }
        }, 25000)
        onUnmounted(() => clearInterval(interval))
    }

    onMounted(() => {
        connect()
        startHeartbeat()
    })

    onUnmounted(() => {
        if (ws.value) {
            ws.value.close(1000, '组件卸载')
        }
    })

    return {
        isConnected,
        sendMessage,
        ws,
        handleMessage,
        subscribe,
        unsubscribe,
        messageCallbacks,
        wsReadyState,
        connect
    }
}